<template>
	<common-card type="form" :title="cardTitle" :loading="loading">
		<el-form ref="form" size="medium" :model="formData" :rules="formRules" :validate-on-rule-change="false" class="formbox">
			<el-form-item label="实验名称" prop="name">
				<el-input v-model="formData.name" placeholder="请输入实验名称"></el-input>
			</el-form-item>
			<el-form-item label="所属课题" prop="topicId">
				<el-select v-model="formData.topicId" placeholder="选择课题名称" style="width: 100%">
					<el-option v-for="(item, index) in topicAuditData" :key="index" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<template v-if="!!formData.topicId">
				<el-form-item class="entire">
					<topic-info :data="checkedTopicData"></topic-info>
				</el-form-item>
				<el-form-item label="测量技术" prop="filed1">
					<el-radio-group v-model="formData.filed1" v-removeAriaHidden>
						<el-radio v-for="(item, index) in topicMeasuringData" :key="index" :label="item">{{ item }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="实验PI" prop="filed2">
					<person-select v-model="formData.filed2" :data="topicPrincipalData" placeholder="请选择实验PI"></person-select>
				</el-form-item>
			</template>
			<el-form-item label="实验人员 :(申请人单位其他参与实验的人员)" class="entire" prop="collaList">
				<user-select ref="user" v-model="formData.collaList" :list="userListData"></user-select>
			</el-form-item>
			<el-form-item label="实验申请文件模板">
				<el-button type="text" class="download" @click="handleDownloadTemp(2)">模板文件</el-button>
			</el-form-item>
			<el-form-item label="实验申请文件上传" prop="fileJson">
				<gx-file-uploader type="5" v-model="formData.fileJson"></gx-file-uploader>
			</el-form-item>
		</el-form>
		<template slot="button">
			<template v-if="userRole === 'member'">
				<el-button type="success" icon="sw-icon-btn-save" :loading="saveLoading" @click="handleSaveData()">保存</el-button>
			</template>
			<el-button type="warning" icon="sw-icon-btn-share" :loading="submitLoading" :disabled="btnDisabled" @click="handleSubmitData()">提交</el-button>
		</template>
	</common-card>
</template>

<script>
import topicInfo from '../topicInfo';
import formMixins from '../formMixins';
import commonCard from '../commonCard';
import { queryPageList, queryUserPageList } from '@/api/business/tbTopic';
import { experimentDetail, addedExperiment, updateExperiment } from '@/api/business/tbExperiment';
export default {
	mixins: [formMixins],
	components: { commonCard, topicInfo },
	data() {
		return {
			formRules: {
				name: [{ required: true, message: '请输入实验名称', trigger: 'blur' }],
				topicId: [{ required: true, message: '请选择课题', trigger: 'change' }],
				filed1: [{ required: true, message: '请选择测量技术', trigger: 'change' }],
				filed2: [{ required: true, message: '请选择强磁场PI', trigger: 'change' }],
				collaList: [{ required: true, message: '请添加实验人员', trigger: 'change' }],
				fileJson: [{ required: true, message: '请上传实验申请文件', trigger: 'change' }]
			},
			topicAuditData: []
		};
	},
	computed: {
		topicId() {
			return this.$route.query.topicid || '';
		},
		cardTitle() {
			return this.addOrEdit ? '申请实验' : '修改实验';
		},
		userListData() {
			return this.dictEnums['EXPERIMENT_WAY'] || [];
		},
		checkedTopicData() {
			let info = this.topicAuditData.find((n) => n.id === this.formData.topicId);
			return !info ? {} : info;
		},
		topicMeasuringData() {
			let measureList = this.checkedTopicData.measureList || [];
			return measureList.map((item) => item.piId);
		},
		topicPrincipalData() {
			let principalList = this.checkedTopicData.piList || [];
			return principalList.map((item) => this.principalData.find((n) => n.id === item.piId));
		},
		topicListRequest() {
			if (this.userRole === 'manager') {
				return queryPageList;
			} else if (this.userRole === 'member') {
				return queryUserPageList;
			}
		}
	},
	watch: {
		dataId: {
			async handler(val) {
				this.formData = { collaList: [] };
				this.loading = true;
				this.btnDisabled = false;
				await this.getTopicAuditData();
				if (!val) {
					this.loading = false;
					if (!this.topicId) return false;
					this.$set(this.formData, 'topicId', this.topicId);
				} else {
					this.formData = await this.getDataDetail(val);
				}
				this.$nextTick(() => {
					this.$refs['form'].clearValidate();
				});
			},
			immediate: true
		}
	},
	methods: {
		//获取课题数据
		async getTopicAuditData() {
			let params = { page: 1, limit: 9999, audit: '1' };
			let result = await this.topicListRequest(params).then((res) => res.data);
			if (result.code === '0') {
				this.topicAuditData = result.data || [];
			}
		},

		//获取数据详情
		async getDataDetail(id) {
			let result = await experimentDetail(id).then((res) => res.data);
			this.loading = false;
			if (result.code === '0') {
				let datas = !!result.data && result.data.length > 0 ? result.data[0] : {};
				let collaList = datas.collaList || [];
				this.$set(datas, 'filed2', [datas.filed2]);
				this.$set(
					datas,
					'collaList',
					collaList.map((n) => {
						return { name: n.name, dept: n.dept, position: n.position, role: n.role, modeType: n.modeType };
					})
				);
				return Promise.resolve(datas);
			}
		},

		//保存数据
		handleSaveData() {
			let params = ['name', 'topicId'];
			this.handleSaveFormData(params);
		},

		//提交数据
		handleSubmitData() {
			this.$refs['form'].validate(async (valid) => {
				let userValid = await this.$refs['user'].validChildForm();
				if (!valid || !userValid) return false;
				this.formData['isSave'] = '1';
				this.submitFormRequest();
			});
		},

		//格式化表单参数
		formatFormParams() {
			let params = this.$lodash.cloneDeep(this.formData);
			if (!!params.filed2) {
				params['filed2'] = params.filed2[0];
			}
			return params;
		},

		//提交表单请求
		async submitFormRequest() {
			let params = this.formatFormParams();
			let callFunction = eval(this.addOrEdit ? addedExperiment : updateExperiment);
			let result = await callFunction(params).then((res) => res.data);
			if (result.code === '0') {
				this.btnDisabled = true;
				this.$showCustomMessage('success', `${this.cardTitle}成功`);
				this.$router.back();
			}
		}
	}
};
</script>

<style lang="scss" scoped></style>